package cn.gcBlock.service.impl;

import cn.gcBlock.service.DigOreService;
import cn.gcBlock.utils.PageUtil;
import cn.gcBlock.po.DigOre;
import cn.gcBlock.repository.DigOreRepository;
import cn.gcBlock.dto.DigOreDTO;
import cn.gcBlock.dto.DigOreQueryCriteria;
import cn.gcBlock.service.mapper.DigOreMapper;
import cn.gcBlock.utils.QueryHelp;
import cn.gcBlock.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Pageable;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Optional;

/**
 * @author jie
 * @date 2019-09-15
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DigOreServiceImpl implements DigOreService {

    @Autowired
    private DigOreRepository digOreRepository;

    @Resource
    private DigOreMapper digOreMapper;

    @Override
    public Object queryAll(DigOreQueryCriteria criteria, Pageable pageable) {
        Page<DigOre> page = digOreRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(digOreMapper::toDto));
    }

    @Override
    public Object queryAll(DigOreQueryCriteria criteria) {
        return digOreMapper.toDto(digOreRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public DigOreDTO findById(Integer id) {
        Optional<DigOre> digOre = digOreRepository.findById(id);
        ValidationUtil.isNull(digOre, "未查到数据");
        return digOreMapper.toDto(digOre.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DigOreDTO create(DigOre resources) {
        DigOre digOre = digOreRepository.findByPublicKey(resources.getPublicKey());
        if (digOre != null) {
            return digOreMapper.toDto(digOre);
        } else {
            resources.setIsStop(true);
            resources.setPower(0);
            resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            return digOreMapper.toDto(digOreRepository.save(resources));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DigOre resources) {
        Optional<DigOre> optionalDigOre = digOreRepository.findById(resources.getId());
        ValidationUtil.isNull(optionalDigOre, "未查到数据");
        DigOre digOre = optionalDigOre.get();
        digOre.copy(resources);
        digOreRepository.save(digOre);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        digOreRepository.deleteById(id);
    }
}